/**
 * 编译环境管理路由
 *
 * Created by snowingsea on 2020/11/03.
 */
const middleware = require('./../middleware');
const PhoenixError = require('../../models/phoenix-error');
const environments = require('../../models/environments');

function getSystemEnvironments(req, res, next) {
  (async () => {
    const { compiler } = req.query;
    const envs = await environments.getEnvironments(
      {},
      { projectId: req.$systemEnvironmentProject._id }
    );
    const resEnvironments = [];
    envs.forEach((env) => {
      if (!env.builtIn) {
        resEnvironments.push(environments.getSummaryJson(env));
        return;
      }
      if (compiler && env.builtIn && env.projectTypes) {
        const envKeys = Object.keys(env.projectTypes);
        let match = false;
        envKeys.forEach((key) => {
          if (key === '*') {
            match = true;
          }
          if (key.indexOf('*') > 0 && compiler.startsWith(key.split('*')[0])) {
            match = true;
          }
          if (key.indexOf('*') < 0 && compiler === key) {
            match = true;
          }
        });
        if (match) {
          resEnvironments.push(environments.getSummaryJson(env));
        }
      }
    });
    res.json({ environments: resEnvironments });
  })().catch((err) => next(new PhoenixError(err)));
}
/**
 * Export model definition object.
 */
module.exports = (app, prefix) => {
  const environmentsURL = `${prefix}/environments.json`;
  const environmentURL = `${prefix}/environments/:environmentId.json`;

  // 获取编译环境信息
  app.get(environmentURL, middleware.user.requireTokenUnexpired);
  app.get(environmentURL, middleware.user.requireAvailable);
  app.get(environmentURL, middleware.user.requireTester);
  app.get(environmentURL, middleware.environment.requireEnvironmentExist);
  app.get(environmentURL, middleware.environment.getEnvironment);

  // 获取编译环境列表
  app.get(environmentsURL, middleware.user.requireTokenUnexpired);
  app.get(environmentsURL, middleware.user.requireAvailable);
  app.get(environmentsURL, middleware.user.requireTester);
  app.get(environmentsURL, middleware.user.getSuperUser);
  app.get(environmentsURL, middleware.environment.requireSystemEnvironmentProjectExist);
  app.get(environmentsURL, getSystemEnvironments);
};
